<?php

/**
 * 后台菜单管理
 * @author  xiaobai
 * @date    2017-01-08
 */

namespace app\panel\controller;

use app\common\controller\Panelbase;
use app\common\model\Menu as menu_model;

class Menu extends Panelbase
{

    public function initialize()
    {
        parent::initialize();
        $this->model = new menu_model();

        $this->assign('displays', menu_model::$displays);
    }

    public function index()
    {
        $list = $this->model->selectMenu();
        $this->assign('lists', $list);
        return $this->fetch();
    }

    public function add()
    {
        $parentid  = input('param.parentid', 0, 'intval');
        $menu_list = $this->model->selectMenu();

        $this->assign('menu_list', $menu_list);
        $this->assign('parentid', $parentid);
        return $this->fetch();
    }

    public function add_post()
    {
        if (request()->isPost()) {
            $data = input('post.');

            // 数据验证
            $result = $this->validate($data,'menu');
            if (true !== $result) {
                $this->error($result);
            }
            
            if ($this->model->insertMenu($data)) {
                del_dir_and_file();
                $this->success('保存成功', Url('index'));
            } else {
                $this->error($this->model->getError());
            }
        } else {
            $this->error('请求错误');
        }
    }

    public function edit()
    {
        $id = input("param.id");
        $menu = $this->model->where('id',$id)->find()->toArray();
        if (empty($menu)) {
            $this->error('数据不存在');
        }

        $menu_list = $this->model->selectMenu();
        
        $this->assign('menu_list', $menu_list);
        $this->assign($menu);

        return $this->fetch();
    }

    public function edit_post()
    {
        if (request()->isPost()) {
            $data = input('post.');
            // 数据验证
            $result = $this->validate($data,'menu');
            if (true !== $result) {
                $this->error($result);
            }

            if ($this->model->updateMenu($data)) {
                del_dir_and_file();
                $this->success('保存成功', Url('index'));
            } else {
                $this->error($this->model->getError());
            }
        } else {
            $this->error('请求错误');
        }
    }

    public function listorders()
    {
        $post = input("post.");
        if (empty($post['sort']) || !is_array($post['sort'])) {
            $this->error('数据不能为空');
        }
        $data = array();
        foreach ($post['sort'] as $key=>$val) {
            $data[$key]['id']   = $key;
            $data[$key]['sort'] = $val;
        }
        $res = $this->model->saveAll($data);
        if ($res !== false) {
            del_dir_and_file();
            $this->success('排序成功');
        } else {
            $this->error('排序失败');
        }
    }

}
